import { applyDecorators, Type } from "@nestjs/common";
import { ApiExtraModels, ApiResponse, getSchemaPath } from "@nestjs/swagger";

const baseTypeNames = ["String", "Number", "Boolean"];

/**
 * @description: 生成返回结果装饰器
 */
export const APIResponse = <TModel extends Type<any>>(
  type?: TModel | TModel[] | any,
  isPage?: boolean
) => {
  let prop = null;
  if (Array.isArray(type)) {
    if (isPage) {
      prop = {
        type: "object",
        properties: {
          list: {
            type: "array",
            items: { $ref: getSchemaPath(type[0]) },
          },
          total: { type: "number", default: 0 },
        },
      };
    } else {
      prop = {
        type: "array",
        list: { $ref: getSchemaPath(type[0]) },
      };
    }
  } else if (type) {
    if (type && baseTypeNames.includes(type.name)) {
      prop = { type: type.name.toLocaleLowerCase() };
    } else if (getSchemaPath(type).indexOf("undefined") == -1) {
      prop = { $ref: getSchemaPath(type) };
    } else {
      prop = { type: typeof type, default: type };
    }
  } else {
    prop = { type: "null", default: null };
  }

  let resProps = {
    type: "object",
    properties: {
      code: { type: "number", default: 200 },
      msg: { type: "string", default: "ok" },
      data: prop,
    },
  };

  return applyDecorators(
    ApiExtraModels(type ? (Array.isArray(type) ? type[0] : type) : String),
    ApiResponse({
      schema: {
        allOf: [resProps],
      },
    })
  );
};
